/**
 * 
 */
package anyware.desktop.task;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import javax.annotation.Resource;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import anyware.desktop.DesktopService;

/**
 * @author keke
 * 
 */
@Scope("prototype")
@Component("fileSyncTask")
public class FileSyncTask {
    private static final Logger LOG = LoggerFactory
                                            .getLogger(FileSyncTask.class);

    /**
     * @param args
     */
    public static void main(final String[] args) {

    }

    private DesktopService desktopService;

    @Resource
    public void setDesktopService(final DesktopService desktopService) {
        this.desktopService = desktopService;
    }

    public void sync(final File root) {
        Validate.notNull(root, "Root should not be null");
        Validate.isTrue(root.isDirectory() && root.exists(),
                "Root should be an existed directory");
        scanRoot(root);
    }

    public void syncAll() throws IOException {
        if(LOG.isInfoEnabled()){
            LOG.info("Start sync all roots");
        }
        final Collection<File> roots = desktopService.getSyncRoots();
        for (final File root : roots) {
            sync(root);
        }
    }

    private void scanRoot(final File root) {
        assert root != null;
        assert root.exists() && root.isDirectory();
        if(LOG.isDebugEnabled()){
            LOG.debug("Scan root: {}",root);
        }
        final File[] files = root.listFiles();
        for (final File file : files) {
            if (file.isDirectory()) {
                scanRoot(file);
            } else {
                // sync this file.
                desktopService.syncFile(file);
            }
        }
    }

}
